package pps.et5.eit.ex2;

import java.awt.event.TextListener;
import java.io.InputStreamReader;
import java.util.Scanner;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.InitialContext;

import pps.et5.eit.ex1.Consumer;

public class Client implements MessageListener{

	private ConnectionFactory connectionFactory; 
	private Destination request, response;
	
	public static void main(String[] args) { 
		try {
			Client client = new Client(); 
			client.connect(); 
			client.waitForMessage();
		} catch (Throwable t) { 
			t.printStackTrace();
		} 
	}
	private void waitForMessage() throws Exception {
		String smes = new String();
		
		// Créer une connexion au système de messagerie
		// Et affiche les messages au fur et à mesure de leur arrivée dans la queue
		// Création d'une Connexion et d'une Session
		Connection connection = connectionFactory.createConnection();
		Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		
		
		
		// Création d'un MessageConsumer et d'un MessageProducer
		
		MessageConsumer consumer = session.createConsumer(response);
		MessageProducer producer = session.createProducer(request);
		
		// Reception des messages
		consumer.setMessageListener(this);
		connection.start();
		
		// Emission du message
		System.out.println("Taper le message à inverser (Q pour quitter)");
		Scanner inputStream = new Scanner(System.in);
		
		while ( !(smes.compareTo("Q") == 0) ) {
			smes = inputStream.nextLine();
			TextMessage message = session.createTextMessage(smes);
			producer.send(message);
		}
		
		
		// Fermeture de la connexion
		connection.close();
	}
	private void connect() throws Exception {
		// Initialise les attributs connectionFactory et destination.
		// Création d'un contexte JNDI
		InitialContext jndiContext = new InitialContext();
		// Lookup de la fabrique de connexion et de la destination
		connectionFactory = (ConnectionFactory) jndiContext.lookup("connectionFactory"); 
		request = (Destination) jndiContext.lookup("Request");
		response = (Destination) jndiContext.lookup("Response");
	}
	
	@Override
	public void onMessage(Message message) {
		TextMessage text = (TextMessage) message;

	     try {
	    	 if (text instanceof TextMessage) {
	    		 System.out.println("Message: " + text.getText());
	    	 }
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
}
